package busi

import (
	"encoding/json"
	"fmt"
	"go.uber.org/zap"
	"hisim/global"
	"net/http"
	"time"
)

type PatientCallListData struct {
	PackID       string                     `json:"PackID"`
	WardNo       string                     `json:"WardNo"`
	PatientID    string                     `json:"PatientID"`
	Name         string                     `json:"Name"`
	BedNo        string                     `json:"BedNo"`
	ChannelCode  string                     `json:"Channel"`
	Channel      int32                      `json:"-"` //多通道的通道号,原分机为0,新增分机从1开始
	StartTime    string                     `json:"StartTime"`
	MedicineList []*PatientCallMedicineData `json:"MedicineList"`
	Status       int                        `json:"Status"` //1.停止 0.开始
}

type PatientCallMedicineData struct {
	MedicineNo    string `json:"MedicineNo"`
	MedicineName  string `json:"MedicineName"`
	Specification string `json:"Specification"`
	RealAmount    string `json:"RealAmount"`
	Dosage        string `json:"Dosage"`
	InstrCode     string `json:"InstrCode"`
	UseDate       string `json:"UseDate"`
}

type IfsReqInfo struct {
	Id      string `gorm:"primary_key"`
	Request string `gorm:"column:request"`
}

//患者出院
func StartIfs() {
	p := findPatient("in")
	if p == nil {
		return
	}

	var id int
	idList := make([]int, 0)
	if err := db.Table("ifs_report_form").Pluck("id", &idList).Error; err != nil {
		zap.S().Error(err)
		return
	} else if len(idList) == 0 {

	} else {
		n := ra.Intn(len(idList))
		id = idList[n]
	}

	if id == 0 {
		return
	}

	var reqInfo IfsReqInfo
	if err := db.Table("ifs_report_form").Where("id=?", id).Scan(&reqInfo).Error; err != nil {
		zap.S().Error(err)
		return
	}

	var pd PatientCallListData
	if err := json.Unmarshal([]byte(reqInfo.Request), &pd); err != nil {
		fmt.Println("Unmarshal error:", err.Error())
		return
	}

	n1 := ra.Intn(99999)
	n2 := ra.Intn(999)

	now := time.Now()
	pd.StartTime = now.Format(time.DateTime)
	pd.Channel = 0
	pd.Status = 0
	pd.WardNo = p.Area
	pd.BedNo = p.Bed
	pd.PatientID = p.VisitNo
	pd.ChannelCode = "aa"
	//pd.Name = p.Name
	pd.PackID = fmt.Sprintf("%s||%d||%d", p.VisitNo, n1, n2)
	for _, m := range pd.MedicineList {
		m.UseDate = now.Format("2006-01-02 15:04:05")
	}
	//
	var emp Response
	if err := global.HttpRequest[Response]("http://localhost:6060/ifs/infusion/medicine", http.MethodPost, nil, pd, &emp); err != nil {
		fmt.Println(err.Error())
		return
	} else if emp.Status != 200 {
		fmt.Println(emp.Text)
	}
}
